/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.wx.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.common.QiniuUtils;
import com.jeesite.modules.common.refun.CollectionUtil;
import com.jeesite.modules.common.refun.RandomUtil;
import com.jeesite.modules.common.refun.StringUtil;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.wx.entity.*;
import com.jeesite.modules.wx.service.WxActivityService;
import com.jeesite.modules.wx.service.WxBusinessGroupService;
import com.jeesite.modules.wx.service.WxBusinessUserService;
import com.qiniu.common.QiniuException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.wx.service.WxBusinessService;
import org.springframework.web.util.HtmlUtils;

import java.io.File;
import java.util.List;

/**
 * wx_businessController
 * @author wangjianxin
 * @version 2018-09-28
 */
@Controller
@RequestMapping(value = "${adminPath}/wx/wxBusiness")
public class WxBusinessController extends BaseController {

	@Autowired
	private WxBusinessService wxBusinessService;
	@Autowired
	private WxBusinessUserService wxBusinessUserService;
	@Autowired
	private WxBusinessGroupService wxBusinessGroupService;
	@Autowired
	private WxActivityService wxActivityService;

	@Value("${api.host.value}")
	private String hostName;
	@Value("${api.img.path}")
	private String imgPath;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public WxBusiness get(String id, boolean isNewRecord, Model model) {

		WxBusiness wxBusiness =  wxBusinessService.get(id, isNewRecord);
//		List<WxBusiness> list = new LinkedList<>();
//		if(StringUtil.isNotEmpty(wxBusiness.getDetailImg())){
//			String detailImgs = wxBusiness.getDetailImg();
//			String[] detailImgArray = detailImgs.split(",");
//			int len = detailImgArray.length;
//			for (int i = 0; i < len; i++) {
//				String detailImg = detailImgArray[i];
//				if(StringUtil.isEmpty(detailImg)){
//					continue;
//				}
//				WxBusiness w = new WxBusiness();
//				w.setPic(detailImg);
//				list.add(w);
//			}
//			wxBusiness.setDetailImgList(list);
//		}
//
//		model.addAttribute("wxBusiness", wxBusiness);

		return wxBusiness;
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("wx:wxBusiness:view")
	@RequestMapping(value = {"list", ""})
	public String list(WxBusiness wxBusiness, Model model) {
		model.addAttribute("wxBusiness", wxBusiness);
		return "modules/wx/wxBusinessList";
	}

	/**
	 * 商家员工列表
	 */
	@RequiresPermissions("wx:wxBusiness:view")
	@RequestMapping(value = {"user"})
	public String user(WxBusiness wxBusiness, Model model) {
		model.addAttribute("wxBusiness", wxBusiness);
		return "modules/wx/wxBusinessUserFirstList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("wx:wxBusiness:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<WxBusiness> listData(WxBusiness wxBusiness, HttpServletRequest request, HttpServletResponse response,
									 @RequestParam(value = "type",required = false) String type,
									 @RequestParam(value = "activityId",required = false) String activityId) {
		if(StringUtil.isNotEmpty(activityId)){
			WxActivity wxActivity = wxActivityService.get(activityId);
			Long groupId = wxActivity.getBusinessGroupId();
			wxBusiness.setGroupId(groupId);
		}

		Page<WxBusiness> page = wxBusinessService.findPage(new Page<WxBusiness>(request, response), wxBusiness);
		//这里是获取商家的员工信息
		if(StringUtil.isNotEmpty(type) && type.equals("businessUserFirst")){
			for(WxBusiness temp : page.getList()){
				String businessId = temp.getId();
				WxBusinessUser wxBusinessUser = new WxBusinessUser();
				wxBusinessUser.setBusinessId(Long.valueOf(businessId));
				Long count = wxBusinessUserService.findCount(wxBusinessUser);
				if(StringUtil.isNotEmpty(activityId)){
					temp.setActivityId(activityId);
				}
				temp.setUserCount(count);
			}
		}

		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("wx:wxBusiness:view")
	@RequestMapping(value = "form")
	public String form(WxBusiness wxBusiness, Model model) {
		if(null != wxBusiness.getGroupId()){
			wxBusiness.setOldGroupId(wxBusiness.getGroupId());
		}
		model.addAttribute("wxBusiness", wxBusiness);
		return "modules/wx/wxBusinessForm";
	}

	/**
	 * 保存wx_business
	 */
	@RequiresPermissions("wx:wxBusiness:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated WxBusiness wxBusiness) {
		Long oldGroupId = wxBusiness.getOldGroupId();
		logger.info("保存商家获得旧的分组id={}",oldGroupId);
		Long groupId = wxBusiness.getGroupId();
		String pic = wxBusiness.getPic();
		String vipCardImg = wxBusiness.getVipCardImg();
		String radio = wxBusiness.getRadio();
		String detailImgs = wxBusiness.getDetailImg();
		String videoImg = wxBusiness.getVideoImg();


		if(StringUtils.isNotEmpty(pic)){
			File file = new File(imgPath+pic);
			String picName = file.getName();
			logger.info("upload pic file name:"+file.getName());
			try {
				String picUrl = QiniuUtils.upload(file, picName);
				logger.info(picUrl);
				wxBusiness.setPic(picUrl);
			} catch (QiniuException e) {
				logger.error("上传商家pic到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}
		}

		if(StringUtils.isNotEmpty(vipCardImg)){

			File file = new File(imgPath+vipCardImg);
			String vipCardImgName = file.getName();
			logger.info("upload vipCardImg file name:"+file.getName());

			try {
				String picUrl = QiniuUtils.upload(file, vipCardImgName);
				logger.info(picUrl);
				wxBusiness.setVipCardImg(picUrl);
			} catch (QiniuException e) {
				logger.error("上传商家vipCardImg到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}
		}

		if(StringUtils.isNotEmpty(radio)){

			File file = new File(imgPath+radio);
			String radioName = file.getName();
			logger.info("upload radio file name:"+radioName);
			try {
				String radioUrl = QiniuUtils.upload(file, radioName);
				logger.info(radioUrl);
				wxBusiness.setRadio(radioUrl);
			} catch (QiniuException e) {
				logger.error("上传商家radioUrl到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}
		}

		/**
		 * 商家详情图片
		 */
		if(StringUtils.isNotEmpty(detailImgs)) {

			String[] detailImgArray = detailImgs.split("\\|");
			int len = detailImgArray.length;

			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < len; i++) {
				String detailImg = detailImgArray[i];
				File file = new File(imgPath + detailImg);
				String detailImgName = file.getName();
				logger.info("upload detailImg file name:" + detailImgName);
				try {
					String detailImgUrl = QiniuUtils.upload(file, detailImgName);
					logger.info(detailImgUrl);
					sb.append(detailImgUrl+",");
				} catch (QiniuException e) {
					logger.error("上传商家detailImgs到七牛云失败={}", e.getMessage());
					e.printStackTrace();
				}
			}
			if(sb.length() != 0){
				wxBusiness.setDetailImg(sb.toString());
			}
		}

		/**
		 * 视频缩略图
		 */
		if(StringUtils.isNotEmpty(videoImg)) {

			File file = new File(imgPath+videoImg);
			String videoImgName = file.getName();
			logger.info("upload videoImg file name:"+file.getName());

			try {
				String picUrl = QiniuUtils.upload(file, videoImgName);
				logger.info(picUrl);
				wxBusiness.setVideoImg(picUrl);
			} catch (QiniuException e) {
				logger.error("上传商家videoImg到七牛云失败={}",e.getMessage());
				e.printStackTrace();
			}
		}

		//避免修改
		if(StringUtil.isEmpty(wxBusiness.getHexiaoPassword())){
			//核销密码
			String random = "";
			//检查是否存在
			while (true){
				random = RandomUtil.getFiveRandom();
				WxBusiness c = new WxBusiness();
				c.setHexiaoPassword(random);
				List<WxBusiness> wxBusinessList = wxBusinessService.findList(c);
				if(CollectionUtil.isEmpty(wxBusinessList)){
					break;
				}
			}
			wxBusiness.setHexiaoPassword(random);
		}

		//页面转译
		wxBusiness.setContent(HtmlUtils.htmlUnescape(wxBusiness.getContent()));
		wxBusinessService.save(wxBusiness);

		//商家分组,这里涉及到商家切换分组后，需要删除之前分组的中businessIds中的旧数据
		if(null != groupId){
			//判断之前是否绑定过其他分组，需要解除
			if(null != oldGroupId && !oldGroupId.equals(groupId)){
				wxBusinessGroupService.removeBusinessId(oldGroupId,wxBusiness.getId());
			}

			WxBusinessGroup wxBusinessGroup = new WxBusinessGroup();
			wxBusinessGroup.setConfigGroupId(groupId);
			List<WxBusinessGroup> wxBusinessGroupList = wxBusinessGroupService.findList(wxBusinessGroup);
			if(CollectionUtil.isNotEmpty(wxBusinessGroupList)){
				WxBusinessGroup find = wxBusinessGroupList.get(0);
				String oldBusinessIds = find.getBusinessIds();
				if(StringUtil.isNotEmpty(oldBusinessIds)){
					if(oldBusinessIds.contains(wxBusiness.getId())){
						logger.info("分组中存在该商家");
					}else{
						find.setBusinessIds(oldBusinessIds+","+wxBusiness.getId());
					}
				}else{
					find.setBusinessIds(wxBusiness.getId());
				}
				wxBusinessGroupService.save(find);
			}else{
				WxBusinessGroup saveBusinessGroup = new WxBusinessGroup();
				//分组id
				saveBusinessGroup.setConfigGroupId(groupId);
				//机构code码
				Employee employee = (Employee) UserUtils.getUser().getRefObj();
				saveBusinessGroup.setOfficeCode(employee.getOffice().getOfficeCode());
				//商家id
				saveBusinessGroup.setBusinessIds(wxBusiness.getId());
				wxBusinessGroupService.save(saveBusinessGroup);
			}

			//获得此商家对应的活动,更新活动缓存数据
			try {
				wxBusinessService.updateCache(wxBusiness);
			}catch (Exception e){
				e.printStackTrace();
				logger.error("更新活动缓存数据错误");
			}
		}
		return renderResult(Global.TRUE, text("保存商家成功！"));
	}
	
	/**
	 * 删除wx_business
	 */
	@RequiresPermissions("wx:wxBusiness:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(WxBusiness wxBusiness) {
		wxBusinessService.delete(wxBusiness);
		return renderResult(Global.TRUE, text("删除商家成功！"));
	}

	/**
	 * 根据分组id查询分组下的所有商家信息list
	 * @param groupId
	 * @return
	 */
	@RequestMapping("getBusinessByGroupId")
	@ResponseBody
	public List<WxBusiness> getBusinessByGroupId(String groupId){
		WxBusiness wxBusiness = new WxBusiness();
		wxBusiness.setGroupId(Long.valueOf(groupId));
		List<WxBusiness> wxBusinessList = wxBusinessService.findList(wxBusiness);
		return wxBusinessList;
	}



}